from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockHolderChange(Base):
    __tablename__ = 'stock_holder_change'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    jzrq = Column(String(10))
    gdhs = Column(String(255))
    bh = Column(String(20))

    def __init__(self, code, jzrq, gdhs, bh):
        self.code = code
        self.jzrq = jzrq
        self.gdhs = gdhs
        self.bh = bh

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_stock_holder_change = session.query(StockHolderChange).filter_by(code=code,
                                                                                      jzrq=data['jzrq']).first()
            if existing_stock_holder_change:
                existing_stock_holder_change.gdhs = data['gdhs']
                existing_stock_holder_change.bh = data['bh']
            else:
                session.add(StockHolderChange(code=code, jzrq=data['jzrq'], gdhs=data['gdhs'],
                                              bh=data['bh']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
